<?php
/**
 * Created by PhpStorm.
 * Script Name: MpTemplateMsg.php
 * Create: 2023/1/11 16:10
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\service;

use plugin\wechat\app\model\Mp;
use plugin\wechat\app\model\MpTemplatemsgTask as TaskM;

class MpTemplateMsg
{
    static function statusList($id = null){
        $list = [
            0 => '待发送',
            1 => '发送中',
            2 => '已完成',
            3 => '已终止'
        ];
        return isset($list[$id]) ? $list[$id] : $list;
    }

    /**
     * 获取正在进行中的活动数据
     * @param int $task_id
     * @return array|mixed|\think\db\Query|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function getTodoTask($task_id = 0){
        return $task = TaskM::alias('task')
            ->join('wechat_mp_templatemsg msg', 'msg.id=task.templatemsg_id')
            ->field(['task.*', 'msg.template_id', 'msg.content', 'msg.url', 'msg.speed'])
            ->where([
                ['task.id','=', $task_id],
                ['task.status', 'in', [0, 1]],
                ['push_time' ,'<=', time()]
            ])->find();
    }

    /**
     * 更新任务
     * @param array $update
     * @return \think\Model
     * @throws \think\db\exception\DbException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function updateTask($update = []){
        return TaskM::update($update);
    }

    /**
     * 获取mp 信息
     * @param int $mp_id
     * @return mixed|\think\Model
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function getMpById($mp_id = 0){
        $key = wechat_cache_key(__FUNCTION__ . $mp_id);
        $data = cache($key);
        if(empty($data)){
            $data = Mp::find($mp_id);
        }
        return $data;
    }
}